package com.artisan.view;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;

import com.artisan.dao.AdminDao;
import com.artisan.dao.StudentDao;
import com.artisan.dao.TeacherDao;
import com.artisan.model.Admin;
import com.artisan.model.Student;
import com.artisan.model.Teacher;
import com.artisan.model.UserType;
import com.artisan.util.StringUtil;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginFrm extends JFrame {

	private JPanel contentPane;
	private JPasswordField passwordtextField;
	private JTextField userNametextField;
	private JComboBox userTypeComboBox;
	private JButton loginButton;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LoginFrm frame = new LoginFrm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public LoginFrm() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(LoginFrm.class.getResource("/com/artisan/image/学生管理.png")));
		setFont(new Font("微软雅黑", Font.PLAIN, 14));
		setTitle("登陆界面");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 662, 430);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

		setContentPane(contentPane);
		setLocationRelativeTo(null);

		JLabel lblNewLabel = new JLabel("学生信息管理系统登陆界面");
		lblNewLabel.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/学生.png")));
		lblNewLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));

		JLabel lblNewLabel_1 = new JLabel(" 用 户 名：");
		lblNewLabel_1.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/用户名.png")));
		lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		JLabel lblNewLabel_2 = new JLabel("密       码：");
		lblNewLabel_2.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/密码.png")));
		lblNewLabel_2.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		passwordtextField = new JPasswordField();
		passwordtextField.setColumns(10);

		JLabel lblNewLabel_3 = new JLabel("用户类型：");
		lblNewLabel_3.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/userType.png")));
		lblNewLabel_3.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		userTypeComboBox = new JComboBox();
		userTypeComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		userTypeComboBox.setModel(
				new DefaultComboBoxModel(new UserType[] { UserType.ADMIN, UserType.TEACHER, UserType.STUDENT }));

		userNametextField = new JTextField();
		userNametextField.setColumns(10);

		loginButton = new JButton("登录");
		passwordtextField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent ae) {
				if (ae.getKeyChar() == KeyEvent.VK_ENTER) {
					// 此处为要按下回车后触发的动作，应与按下登录按钮后实现的功能相同
					login();
				}
			}
		});
		loginButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				login();
			}
		});
		loginButton.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/登录.png")));
		loginButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		JButton resetButton = new JButton("重置");
		resetButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				resetValue(ae);
			}
		});
		resetButton.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/重置.png")));
		resetButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		JButton enrollButton = new JButton("注册");
		enrollButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				enrollAct(ae);
			}
		});
		enrollButton.setIcon(new ImageIcon(LoginFrm.class.getResource("/com/artisan/image/添加.png")));
		enrollButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addGroup(gl_contentPane
				.createSequentialGroup()
				.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane
						.createSequentialGroup().addGap(202).addComponent(loginButton).addGap(18)
						.addComponent(enrollButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED, 25, Short.MAX_VALUE).addComponent(resetButton))
						.addGroup(gl_contentPane.createSequentialGroup().addGap(161).addGroup(gl_contentPane
								.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
										.addComponent(lblNewLabel_2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE,
												GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(lblNewLabel_1, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 78,
												Short.MAX_VALUE))
								.addComponent(lblNewLabel_3)).addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
										.addComponent(userTypeComboBox, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(passwordtextField).addComponent(userNametextField,
												GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)))
						.addGroup(gl_contentPane.createSequentialGroup().addGap(177).addComponent(lblNewLabel,
								GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)))
				.addGap(126)));
		gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane
				.createSequentialGroup().addContainerGap()
				.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 77, GroupLayout.PREFERRED_SIZE).addGap(41)
				.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_1, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
						.addComponent(userNametextField, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE))
				.addGap(30)
				.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel_2)
						.addComponent(passwordtextField, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE))
				.addGap(37)
				.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_3, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)
						.addComponent(userTypeComboBox, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE))
				.addGap(18)
				.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
						.addComponent(enrollButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE).addComponent(loginButton)
								.addComponent(resetButton, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)))
				.addGap(21)));
		contentPane.setLayout(gl_contentPane);
	}

	protected void enrollAct(ActionEvent ae) {
		// TODO 自动生成的方法存根
		UserType selectedItem = (UserType) userTypeComboBox.getSelectedItem();
		if ("学生".equals(selectedItem.getName())) {
			String userName = userNametextField.getText().toString();
			String userPassword = String.valueOf(passwordtextField.getPassword());
			if (StringUtil.isEmpty(userName)) {
				JOptionPane.showMessageDialog(this, "请填写用户姓名!");
				return;
			}
			if (StringUtil.isEmpty(userPassword)) {
				JOptionPane.showMessageDialog(this, "请填写密码!");
				return;
			}
			Student student = new Student();
			student.setName(userName);
			student.setPassword(userPassword);
			StudentDao studentDao = new StudentDao();
			if (studentDao.isStudentSelected(student)) {
				JOptionPane.showMessageDialog(this, "该用户已存在,请重新注册!");
				return;
			} else {
				if (studentDao.enrollStudent(student)) {
					JOptionPane.showMessageDialog(this, "注册成功!");
				} else {
					JOptionPane.showMessageDialog(this, "注册失败!");
				}
			}
		} else if ("系统管理员".equals(selectedItem.getName())) {
			String userName = userNametextField.getText().toString();
			String userPassword = String.valueOf(passwordtextField.getPassword());
			Date date = new Date();
			DateFormat formatType = new SimpleDateFormat("YYYY-MM-dd-HH-mm-ss");
			String createTime = formatType.format(date);
			if (StringUtil.isEmpty(userName)) {
				JOptionPane.showMessageDialog(this, "请填写用户姓名!");
				return;
			}
			if (StringUtil.isEmpty(userPassword)) {
				JOptionPane.showMessageDialog(this, "请填写密码!");
				return;
			}
			Admin admin = new Admin();
			admin.setName(userName);
			admin.setPassword(userPassword);
			admin.setCreateDate(createTime);
			AdminDao adminDao = new AdminDao();
			if (adminDao.isAdminSelected(admin)) {
				JOptionPane.showMessageDialog(this, "该用户已存在,请重新注册!");
				return;
			} else {
				if (adminDao.enrollAdmin(admin)) {
					JOptionPane.showMessageDialog(this, "注册成功!");
				} else {
					JOptionPane.showMessageDialog(this, "注册失败!");
				}
			}
		} else if ("教师".equals(selectedItem.getName())) {
			String userName = userNametextField.getText().toString();
			String userPassword = String.valueOf(passwordtextField.getPassword());
			if (StringUtil.isEmpty(userName)) {
				JOptionPane.showMessageDialog(this, "请填写注册姓名!");
				return;
			}
			if (StringUtil.isEmpty(userPassword)) {
				JOptionPane.showMessageDialog(this, "请填写注册密码!");
				return;
			}
			Teacher teacher = new Teacher();
			teacher.setName(userName);
			teacher.setPassword(userPassword);
			TeacherDao teacherDao = new TeacherDao();
			if (teacherDao.isTeacherSelected(teacher)) {
				JOptionPane.showMessageDialog(this, "该用户已存在,请重新注册!");
				return;
			} else {
				if (teacherDao.enrollTeacher(teacher)) {
					JOptionPane.showMessageDialog(this, "注册成功!");
				} else {
					JOptionPane.showMessageDialog(this, "注册失败!");
				}
			}
		}
	}

	protected void resetValue(ActionEvent ae) {
		// TODO 自动生成的方法存根
		userNametextField.setText("");
		passwordtextField.setText("");
		userTypeComboBox.setSelectedIndex(0);
	}

	private void login() {
		String userName = userNametextField.getText().toString();
		String password = String.valueOf(passwordtextField.getPassword());
		UserType selectedItem = (UserType) userTypeComboBox.getSelectedItem();
		if (StringUtil.isEmpty(userName)) {
			JOptionPane.showMessageDialog(this, "用户名不能为空");
			return;
		}
		if (StringUtil.isEmpty(password)) {
			JOptionPane.showMessageDialog(this, "密码不能为空");
			return;
		}
		Admin admin = null;
		if ("系统管理员".equals(selectedItem.getName())) {
			// 系统管理员登录
			AdminDao adminDao = new AdminDao();
			Admin adminTmp = new Admin();
			adminTmp.setName(userName);
			adminTmp.setPassword(password);
			admin = adminDao.login(adminTmp);
			adminDao.closeDao();
			if (admin == null) {
				JOptionPane.showMessageDialog(this, "用户名或密码错误!\n或检查您的身份选择!");
				return;
			}
			JOptionPane.showMessageDialog(this, "欢迎【" + selectedItem.getName() + "】" + admin.getName() + "\n登录本系统!",
					"登录提醒", -1);
			this.dispose();
			new MainFrm(selectedItem, admin).setVisible(true);
		} else if ("教师".equals(selectedItem.getName())) {
			// 教师登录
			Teacher teacher = null;
			TeacherDao teacherDao = new TeacherDao();
			Teacher teacherTmp = new Teacher();
			teacherTmp.setName(userName);
			teacherTmp.setPassword(password);
			teacher = teacherDao.login(teacherTmp);
			teacherDao.closeDao();
			if (teacher == null) {
				JOptionPane.showMessageDialog(this, "用户名或密码错误!\n或检查您的身份选择!");
				return;
			}
			JOptionPane.showMessageDialog(this, "欢迎【" + selectedItem.getName() + "】" + teacher.getName() + "登录本系统!",
					"登录提醒", -1);
			this.dispose();
			new MainFrm(selectedItem, teacher).setVisible(true);
		} else {
			// 学生登录
			Student student = null;
			StudentDao studentDao = new StudentDao();
			Student studentTmp = new Student();
			studentTmp.setName(userName);
			studentTmp.setPassword(password);
			student = studentDao.login(studentTmp);
			studentDao.closeDao();
			if (student == null) {
				JOptionPane.showMessageDialog(this, "用户名或密码错误!\n或检查您的身份选择!");
				return;
			}
			JOptionPane.showMessageDialog(this, "欢迎【" + selectedItem.getName() + "】" + student.getName() + "登录本系统!",
					"登录提示", -1);
			this.dispose();
			new MainFrm(selectedItem, student).setVisible(true);
		}
	}
}
